package com.ma.graph.mst;

/**
 * 并查集类
 * 提供接口  boolean connected(int p, int q);
 * void union(int p,int q);
 * int count();
 */
public class UF {
    //联通分量
    private int count;
    //记录该节点的根节点
    private int[] parent;
    //记录节点对应树的节点数
    private int[] size;

    public UF(int n) {
        this.count = n;
        this.parent = new int[n];
        this.size = new int[n];
        for (int i = 0; i < n; i++) {
            this.parent[i] = i;
            this.size[i] = 1;
        }
    }

    public void union(int p, int q) {
        if (find(p) == find(q)) {
            return;
        }
        //小树连接到大树上
        if (size[find(p)] > size[find(q)]) {
            parent[find(q)] = find(p);
            size[find(p)] += size[find(q)];
        } else {
            parent[find(p)] = find(q);
            size[find(q)] += size[find(p)];
        }
        count--;
    }

    public boolean connected(int p, int q) {
        return find(p) == find(q);
    }

    //返回目标节点的根节点
    public int find(int x) {
        while (parent[x] != x) {
            //路径压缩
            parent[x] = parent[parent[x]];
            x = parent[x];
        }
        return x;
    }

    //返回连通分量
    public int getCount() {
        return count;
    }
}
